package com.wangshouyu.mp.pay.unified;

import com.wangshouyu.mp.pay.common.constant.Constant;
import com.wangshouyu.mp.pay.common.constant.UrlConstant;
import com.wangshouyu.mp.pay.common.enums.SignType;
import com.wangshouyu.mp.pay.common.utils.HttpUtils;
import com.wangshouyu.mp.pay.common.utils.SignUtils;
import com.wangshouyu.mp.pay.common.utils.XmlUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.UUID;

/**
 * @author 王守钰
 * @description 统一下单工具类
 * @date 2020/8/13 11:56
 */
public class UnifiedUtils {

    private static Logger log = LoggerFactory.getLogger(UnifiedUtils.class);

    private UnifiedUtils(){}

    /**
     * 统一下单
     * @param unifiedRequest 统一下单请求信息
     * @return 统一下单返回结果
     */
    public static UnifiedResponse unified(UnifiedRequest<? extends BaseUnifiedRequest> unifiedRequest){
        // 付款码支付
        if(unifiedRequest.getRequest() instanceof MicropayUnifiedRequest){

        }
        unifiedRequest.getRequest().setSign(SignUtils.sign(unifiedRequest.getRequest(),unifiedRequest.getKey()));
        String requestXml = XmlUtils.object2Xml(unifiedRequest.getRequest());
        log.info("wechat unified request xml:{}", requestXml);
        String responseXml = null;
        try {
            responseXml = HttpUtils.postXml(UrlConstant.UNIFIED_URL, requestXml);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            throw new UnifiedException(e);
        }
        log.info("wechat unified response xml:{}", responseXml);
        return XmlUtils.xml2Bean(responseXml, UnifiedResponse.class);
    }

    /**
     * 构建支付请求
     * @param unifiedRequest 统一下单请求
     * @return jsapi构造请求信息
     */
    public static JsApiBrandPay brandPay(UnifiedRequest<? extends BaseUnifiedRequest> unifiedRequest){
        UnifiedResponse unifiedResponse = unified(unifiedRequest);
        String nonceStr = UUID.randomUUID().toString().replaceAll("-","");
        JsApiBrandPay brandPay = new JsApiBrandPay();
        brandPay.setAppId(unifiedRequest.getAppId());
        brandPay.setNonceStr(nonceStr);
        brandPay.setPackageStr(Constant.PREPAY_ID_PARAM + unifiedResponse.getPrepayId());
        brandPay.setSignType(SignType.MD5.getType());
        brandPay.setTimeStamp(String.valueOf(System.currentTimeMillis() / 1000));
        brandPay.setPaySign(SignUtils.sign(brandPay, unifiedRequest.getKey()));
        return brandPay;
    }
}
